﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MvcMall.Core.Commands;
using MvcMall.Core.Contacts.Tasks;
using MvcMall.Framework.UnitOfWork;

namespace MvcMall.AdminWeb.Manage.AdminPowers
{
    public partial class SavePower : ManageBasePage
    {
        private IAdminPowerTask _adminPowerTask;
        private IAdminModulTask _adminModulTask;
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidatePagePower("AdminPowerIndex");
            _adminPowerTask = GetInstance<IAdminPowerTask>();
            _adminModulTask = GetInstance<IAdminModulTask>();

            if (!IsPostBack)
            {
                ddlModuls.DataSource = _adminModulTask.GetAll();
                ddlModuls.DataBind();

                var powerId = 0;
                if (Request.QueryString["Id"] != null && Int32.TryParse(Request.QueryString["Id"], out powerId))
                {
                    var info = _adminPowerTask.Get(powerId);
                    if (info == null)
                    {
                        ShowMsgAndReturn("参数错误");
                        return;
                    }

                    lblPowerId.Text = info.Id.ToString();
                    txtPowerName.Text = info.PowerName;
                    txtPowerCode.Text = info.PowerCode;
                    ddlModuls.SelectedIndex =
                        ddlModuls.Items.IndexOf(ddlModuls.Items.FindByValue(info.AdminModul.Id.ToString()));
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var powerName = txtPowerName.Text.Trim();
            var powerCode = txtPowerCode.Text.Trim();
            if (string.IsNullOrEmpty(powerName) || string.IsNullOrEmpty(powerCode))
            {
                ShowMsg("输入有误");
                return;
            }

            var cmd = new SaveAdminPowerCommand
                          {
                              ModulId = Convert.ToInt32(ddlModuls.SelectedValue),
                              PowerCode = powerCode,
                              PowerName = powerName,
                              PowerId =
                                  string.IsNullOrEmpty(lblPowerId.Text) ? (int?)null : Convert.ToInt32(lblPowerId.Text),
                          };

            using (var work = UnitOfWork.Begin())
            {
                if (_adminPowerTask.Save(cmd) != null)
                {
                    work.Commit();
                    ShowMsg("保存成功", "/Manage/AdminPowers/Index.aspx");
                }
                else
                {
                    ShowMsg("保存失败");
                }
            }
        }
    }
}